<template>
  <div class='container-questions-new'>
    <el-card>
      <!-- 标题 -->
      <div
        slot="header"
        class="clearfix"
      >
        <span>试题录入</span>
      </div>
      <!-- 表单 -->
      
          <el-form
            style="margin-left:50px"
            :model="form"
            :rules="rules"
            ref="form"
          >
            <el-form-item
              label="学科:"
              prop="subjectID"
            >
              <el-select
                v-model="form.subjectID"
                class="selectForm"
                 @change="onCatalogue(form.subjectID)"
              >
              <el-option
                  v-for="item in subjectsList"
                  :key="item.index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <!-- 目录 -->
            <el-form-item
              label="目录:"
              prop="catalogID"
            >
              <el-select
                v-model="form.catalogID"
                class="selectForm"
              >
                <el-option
                  v-for="item in catalogue"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
            <!-- 企业 -->
            <el-form-item
              label="企业:"
              prop="enterpriseID"
            >
              <el-select
                v-model="form.enterpriseID"
                class="selectForm"
              >
              <el-option
                  v-for="item in companyList"
                  :key="item.index"
                  :label="item.company"
                  :value="item.company"
                />
              </el-select>
            </el-form-item>
            <!-- 城市 -->
            <el-form-item label="城市:" prop="province">
              <el-select
                v-model="form.province"
                class="chengshi"
                @change="selectProvince(form.province)"
              >
              <el-option
                  v-for="item  in provinces"
                  :key="item.index"
                  :label="item"
                  :value="item"
                  
                />
              </el-select>
              <el-select
                v-model="form.city"
                class="diqu"
              >
              <el-option
                  v-for="item in citys"
                  :key="item.index"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <!-- 方向 -->
            <el-form-item
              label="方向:"
              prop="direction"
            >
              <el-select
                v-model="form.direction"
                class="selectForm"
              >
               <el-option
                  v-for="item  in directions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <!-- 题型 -->
            <el-form-item
              label="题型:"
              prop="questionType"
            >
              <el-radio-group v-model="form.questionType">
                <el-radio :label="1" value="1">单选</el-radio>
                <el-radio :label="2" value="2">多选</el-radio>
                <el-radio :label="3" value="3">简答</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 难度 -->
            <el-form-item
              label="难度:"
              prop="difficulty"
            >
              <el-radio-group v-model="form.difficulty">
                <el-radio :label="1">简单</el-radio>
                <el-radio :label="2">一般</el-radio>
                <el-radio :label="3">困难</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 题干 -->
            <el-form-item
              label="题干:"
              prop="question"
            >
              <quill-editor
                ref="myQuillEditor"
                v-model="form.question"
                :options="editorOption"
                id="editor"
                style="marginLeft:40px"
              />
            </el-form-item>
            <!--选项  -->
            <el-form-item label="选项:" v-if="form.questionType!==3" style="margin-top:80px">
              <el-radio-group v-model="form.check" v-if="form.questionType === 1" @change="hradioChange" >
                <div class="col" v-for=" (item, index) in options " :key="index">
                  <div class="row">
                    <!-- a 选项部分 -->
                    <!-- <el-checkbox :label="item.code" ></el-checkbox> -->
                    <el-radio :label="item.code" ></el-radio>
                    <el-input v-model="item.title"></el-input>
                    <el-upload
                      action=""
                      class="avatar-uploader"
                      
                      :show-file-list="false"
                    >
                    <img
                      v-if="item.imageUrl"
                      :src="item.imageUrl"
                      class="avatar"
                    />
                    <i v-else class="avater-text">上传图片</i>
                </el-upload>
              </div>
          </div>
        </el-radio-group>
        <!-- 复选框 输入框 上传  -->
        <el-checkbox-group v-model="form.checkList" v-else-if="form.questionType === 2" @change="hcheckboxChange" >
          <div class="col" v-for=" (item, index) in options " :key="index">
            <div class="row">
              <!-- a 选项部分 -->
              <el-checkbox  :label="item.code" v-if="form.questionType === 2"></el-checkbox>
              <!-- <el-radio :label="item.code"  v-else-if="form.userType === '单选'"></el-radio> -->
              <el-input v-model="item.title" style="width:300px;margin-left:30px"></el-input>
              <el-upload
                action=""
                class="avatar-uploader"
                :http-request="hUpload"
                :show-file-list="false"
              >
                <img
                  v-if="item.imageUrl"
                  :src="item.imageUrl"
                  class="avatar"
                />
                <i v-else class="avater-text">上传图片</i>
              </el-upload>
            </div>
          </div>
        </el-checkbox-group>
        <!-- 添加按钮部分 -->
        <div class="row">
          <el-button
            type="danger"
            :disabled="form.questionType === 1 ? true : false"
            @click="haddoption"
            >+增加选项与答案</el-button
          >
        </div>            
        </el-form-item>
            <el-form-item  label="解析视频:" style="margin-top:40px;margin-left:-30px">
              <el-input v-model="form.videoURL" style="width:400px"></el-input>
            </el-form-item>
            <el-form-item  label="答案解析:" prop="answer" style="margin-top:40px;margin-left:-30px">
              <quill-editor
                ref="myQuillEditor"
                v-model="form.answer"
                :options="editorOption"
                id="editor"
                style="marginLeft:70px"
              />
            </el-form-item>
            <el-form-item  label="试题备注:" style="margin-top:80px;margin-left:-30px;">
              <el-input
                type="textarea"
                :rows="4"
                v-model="form.remarks"
                style="width:400px;">
              </el-input>
            </el-form-item>
            <el-form-item label="试题标签:"  style="margin-top:40px;margin-left:-30px;">
              <el-select
              v-model="form.tags"
                class="selectForm"
                multiple
              >
              <el-option v-for="item in tags" :key='item.value' :label='item.label' :value='item.label'></el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="margin-top:40px;margin-left:40px">
              <el-button type="success" v-if="this.$route.query.id" @click="hUpdate">确认修改</el-button>
              <el-button  type="primary" v-else @click="onSubmit" >确认提交</el-button>
            </el-form-item>
          </el-form>
        
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import { direction, difficulty } from '@/api/hmmm/constants'
import { datas,provinces,citys } from '@/api/hmmm/citys'
import { simple as subjectsList } from '@/api/hmmm/subjects' // 学科
import { simple as catalogue } from '@/api/hmmm/directorys' // 目录
import { list as companyList } from '@/api/hmmm/companys'
import { simple as tagsList } from '@/api/hmmm/tags' // 标签
import { add, update, detail } from '@/api/hmmm/questions.js'


// 工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  ['blockquote'], // 引用  代码块-----['blockquote', 'code-block']
  ['code-block', 'image', 'link'] // 链接、图片、视频-----['link', 'image', 'video']
]

export default {
  data () {
    return {
      context: '',
      // 富文本编辑配置
      editorOption: {
        // 富文本编辑器配置
        modules: {
          toolbar: toolbarOptions
        },
        theme: 'snow',
        placeholder: ''
      },
      form: {
        arr: ['a', 'b', 'c', 'd', 'e', 'f', 'e'],
        flag: 4,
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '', // 题型
        difficulty: '', // 难度
        question: '', // 题干
        check: '', // 单选选项
        checkList:[],//复选框的选择项
        checkOptions:[],//用户的选择项数据
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      // 验证表单
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'blur' }],
        province: [{ required: true, message: '请选择城市', trigger: 'blur' }],
        city: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'blur' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'blur' }],

      },
      options: [
        {
          code: 'A',
          isRight: 'false',
          title: '',
          imageUrl: ''
        },
        {
          code: 'B',
          isRight: 'false',
          title: '',
          imageUrl: ''
        },
        {
          code: 'C',
          isRight: 'false',
          title: '',
          imageUrl: ''
        },
        {
          code: 'D',
          isRight: 'false',
          title: '',
          imageUrl: ''
        }
      ],
      radio: '1',
      textarea: '',
       // 常量数据
      directions: direction, // 方向
      difficulty, // 难度
      datas,
      provinces,
      citys,
      subjectsList, // 学科
      catalogue, // 目录
      companyList,
      tags: ''
      
      
    }
  },
  watch:{
    $route (val) {
      console.log(val.query.id)
      if (val.query.id) {
        this.loadDetail()
      } else {
        this.$refs.form.resetFields()
      }
    }
  },
  created(){
    this.province()
    this.subjectList()
    this.companyLists()
    if (this.$route.query.id) {
      this.loadDetail()
    }
  },
  mounted(){
  },
  components: {
    quillEditor
  },
  
    methods: {
      //城市获取
      async province(){
        this.provinces=await provinces()
        
      },
      async selectProvince(pname){
        this.citys=await citys(pname)
        this.form.city = ''
      },
      // 学科
      async subjectList () {
        const { data: subjectName } = await subjectsList()
        this.subjectsList = subjectName
        
        
    },
       // // 目录获取
      async onCatalogue (subjectID) {
        if (subjectID) {
          const { data: directory } = await catalogue({ subjectID })
          this.catalogue = directory
          const {data} = await tagsList({subjectID})
          this.tags = data
          this.form.tags = ''
          this.form.catalogID = ''
        } else {
          this.catalogue = []
        }
  //       console.log(this.catalogue)
      },
      //企业
      async companyLists(){
        const { data: remarks } = await companyList()
        this.companyList= remarks.items
        // console.log(this.companyList);
      },
      haddoption(){
        this.options.push({
          isRight:'false',
          code:String.fromCharCode(this.options[this.options.length-1].code.charCodeAt(0)+1),
          title:'',
          imageUrl:''
        })
      },
      // 基础题库列表的获取
    async loadDetail () {
      console.log(this.$route.query.id)
      try {
        const res = await detail({ id: this.$route.query.id })
        console.log(res.data)
        // 将获取的数据赋值给数据项
        this.form.subjectID = res.data.subjectID
        this.form.catalogID = res.data.catalogID
        this.form.enterpriseID = res.data.enterpriseID
        this.form.province = res.data.province
        this.form.city = res.data.city
        this.form.direction = res.data.direction
        // 将后台返回的数据进行数据类型转换
        this.form.questionType = Number(res.data.questionType)
        this.form.difficulty = Number(res.data.difficulty)
        // 题干
        this.form.question = res.data.question
        this.form.videoURL = res.data.videoURL
        this.form.answer = res.data.answer
        this.form.remarks = res.data.remarks // 备注
        this.form.tags = res.data.tags
        // 选项
        this.form.checkOptions = res.data.options
        // 多选框的数据回流
        this.form.checkList = this.form.checkOptions.filter(item => item.isRight === 1).map(item => item.code)
        // 单选框的数据回流
        this.form.check = this.form.checkOptions.filter(item => item.isRight === 1).map(item => item.code)[0]
      } catch (err) {
        console.log(err)
      }
    },
       // 单选框表单组发生变化发生的事件
      hradioChange (val) {
      // 1. 获取点击的 code 的值
      this.form.check = val
      // 2. 更改option数据项
      this.options.map((item, index) => {
        if (item.code === val) {
          // 更改当前项的 isRight的值
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
      // 将 isRight为true 的数组 进行筛选出来
      // 将数组赋值给数据项
      this.form.checkOptions = this.options.filter(item => {
        return item.isRight === true
      })
    },
    //  多选框发生变化的时候 发生的事件
    hcheckboxChange (val) {
      this.form.checkList = val
      console.log(val)
      this.options.map((item, index) => {
        if (val.includes(item.code)) {
          // 更改当前的 isRight 值
          item.isRight = true
        } else {
          item.isRight = false
        }
      })
      // 将符合条件的数组筛选出来 赋值给数据线
      this.form.checkOptions = this.options.filter(item => {
        return item.isRight === true
      })
    },
    doSave(){
       this.$refs.form.validate(async (valid) => {
        if (valid) {
          const data = {
            subjectID: this.form.subjectID,
            catalogID: this.form.catalogID,
            enterpriseID: this.form.enterpriseID,
            province: this.form.province,
            city: this.form.city,
            direction: this.form.direction,
            questionType: '' + this.form.questionType,
            answer: this.form.answer,
            difficulty: '' + this.form.difficulty,
            question: this.form.question,
            options: this.form.checkOptions,
            tags: this.form.tags
          }
          console.log('11111', data)
          // 3. 发送请求 提交数据
          const res = await add(data)
          console.log(res)
          // 4.请求成功 提示用户
          this.$message.success('试题录入成功')
          // 5. 请求成功 进行页面跳转
          this.$router.push('/questions/list')
        } else {
          this.$message.error('失败了')
        }
      })
    },
    onSubmit() {
     this.$refs.form.validate(valid=>{
       if(valid){

         this.doSave()
       }
     })
    },
    async LoadUpdate () {
      try {
        const res = await update()
        console.log(res)
      } catch (err) {
        console.log(err)
      }
    },
    // 点击 修改按钮 -- 实现试题修改
    hUpdate () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.doUpdate()
        }
      })
    },
    // 进行 修改 请求发送
    async  doUpdate () {
      // 获取请求参数
      const data = {
        subjectID: this.form.subjectID,
        catalogID: this.form.catalogID,
        enterpriseID: this.form.enterpriseID,
        province: this.form.province,
        city: this.form.city,
        direction: this.form.direction,
        questionType: '' + this.form.questionType,
        answer: this.form.answer,
        difficulty: '' + this.form.difficulty,
        question: this.form.question,
        options: this.form.checkOptions,
        tags: this.form.tags,
        id: Number(this.$route.query.id),
        videoURL: this.form.videoURL,
        remarks: this.form.remarks
      }
      const res = await update(data)
      console.log(res)
      // 1. 修改成功 提示用户修改试题成功
      this.$message.success('试题修改成功')
      // 2.清空表单内容
      this.$refs.form.resetFields()
      // 3.跳转到基础题库
      this.$router.push('/questions/list')
    }
      
      
     
      
    
  }

}
</script>
<style scoped lang='scss'>
.container-questions-new {
  padding: 20px;
  ::v-deep.ql-toolbar.ql-snow {
    padding: 0 8px;
  }
}
.selectForm {
  width: 400px;
}
.chengshi {
  width: 198px;
}
.diqu {
  width: 198px;
  margin-left: 4px;
}
#editor {
  height: 240px;
}

.el-radio-group .col {
  display: flex;
  flex-direction: column;
  .el-radio,
  .el-checkbox {
    margin-bottom: 30px;
    margin-right: 30px;
  }
  // 多选按钮
  .el-checkbox-grop .col {
    display: flex;
    flex-direction: column;
  .el-radio,
  .el-checkbox {
    margin-bottom: 30px;
    margin-right: 30px;
  }
  }
  .el-input {
    width: 300px;
  }
}
// 上传图片
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader {
  text-align: center;
  margin-left: 10px;
  display: inline-block;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avater-text {
  font-size: 14px;
  color: #8c939d;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
